import React, { useState, useEffect } from 'react';
import { Modal, Button, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import CommonTable from '@/components/CommonTable';
import GoodsTable from '@/components/CommonHtml/GoodsTable/index';
import CommonLoading from '@/components/CommonLoading';
import SetGoodsMind from './SetGoodsMind';
import EditChannelModal from '../SmartSetChannel/component/EditChannelModal';
import { EditOutlined } from '@ant-design/icons';
import { formatAmount } from '@/utils/utils.jsx';
import { platformTypeName } from '@/utils/config';
import {
  changeStatus,
  affect,
  getGoodList,
  queryChannelStatistic,
  updateOrderGoods,
} from '../service';
import { findIndex, pull, remove, find } from 'lodash';
import styles from './GoodsList.module.less';
const { confirm } = Modal;

const goodsArr = [
  null,
  '自发拿货商品',
  '代发拿货商品',
  '库存商品',
  '供应商直发商品',
];

export default ({ type, data, roleType, isCache, handleUpdateData }) => {
  // 智能设置和渠道设置弹框
  const [visible, setVisible] = useState(1);

  //当前操作的行信息
  const [item, setItem] = useState({});

  //选中的行id数组
  const [selectRowkeys, setSelectRowkeys] = useState([]);

  const [loading, setLoading] = useState(false);

  //重置
  useEffect(() => {
    setSelectRowkeys([]);
  }, [isCache]);

  const columns = [
    {
      title: '店铺',
      dataIndex: 'storeName',
      key: 'storeName',
      width: 160,
      render: (text, { platType }) => (
        <>
          <p className="table-weight-text">{text}</p>
          <p>{platformTypeName[platType]}</p>
        </>
      ),
    },
    {
      title: '网店商品',
      dataIndex: 'status',
      key: 'status',
      width: 320,
      render: (text, record) => <GoodsTable item={record} />,
    },
    {
      title: '网店SKU编码',
      dataIndex: 'outStoreSku',
      key: 'outStoreSku',
      width: 160,
    },
    {
      title: '价格（元）',
      dataIndex: 'ecGoodsPrice',
      key: 'ecGoodsPrice',
      width: 90,
      render: (text, record) => (
        <span style={{ color: '#FF2D51' }}>
          ¥{formatAmount(record.ecGoodsPrice)}
        </span>
      ),
    },
    {
      title: '匹配状态',
      dataIndex: 'matchType',
      key: 'matchType',
      width: 80,
      render: (text, record) =>
        record.matchType == 0 ? <span>未匹配</span> : <span>已匹配</span>,
    },
    {
      title: '所属供应商',
      dataIndex: 'zjfStoreName',
      key: 'zjfStoreName',
      width: 150,
      // render: (text) =>
      //   (text || []).map((item, index) => {
      //     return (
      //       <React.Fragment key={index}>
      //         <span key={index}>{item}</span>
      //         <br />
      //       </React.Fragment>
      //     );
      //   }),
    },
    {
      title: '销售状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (text, record) =>
        record.status == 0 ? <span>已下架</span> : <span>出售中</span>,
    },
    {
      title: '分配发货渠道',
      dataIndex: 'channelName',
      key: 'channelName',
      width: 160,
      render: (text, record) => (
        <span>
          {text}{' '}
          {type == 4 || record.isCarefullySelected == '1' ? (
            ''
          ) : (
            <EditOutlined
              className="common-color2"
              onClick={() => handleEditChannel(record)}
              style={{ cursor: 'pointer', fontSize: '16px' }}
            />
          )}{' '}
        </span>
      ),
    },
    {
      title: '操作',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 180,
      render: (text, record) => {
        if (record.matchType == 0) {
          return null;
        } else {
          return (
            <span className="opera-span-common">
              {type == 3 ? (
                ''
              ) : (
                <>
                  <span
                    onClick={() => handleSetGoodsType(3, record)}
                    className="common-color1"
                  >
                    设为库存商品
                  </span>
                  <br />
                </>
              )}
              {type == 1 ? (
                ''
              ) : roleType == 'daifa' ? (
                ''
              ) : (
                <>
                  <span
                    onClick={() => handleSetGoodsType(1, record)}
                    className="common-color1"
                  >
                    设为自发拿货商品
                  </span>
                  <br />
                </>
              )}
              {type == 2 ? (
                ''
              ) : record.daiFaflage ? (
                <>
                  <span
                    onClick={() => handleSetGoodsType(2, record)}
                    className="common-color1"
                  >
                    设为代发拿货商品
                  </span>
                  <br />
                </>
              ) : (
                ''
              )}
              {type != 4 && record.flage ? (
                <>
                  <span
                    onClick={() => handleSetGoodsType(4, record)}
                    className="common-color1"
                  >
                    设为供应商直发商品
                  </span>
                  <br />
                </>
              ) : (
                ''
              )}
            </span>
          );
        }
      },
    },
  ];

  // 点击智能设置事件
  const setGoodsMind = async () => {
    setVisible(2);
  };

  //单条点击设置渠道
  const handleEditChannel = (val) => {
    setItem(val);
    setVisible(3);
  };

  //单个设置商品
  const handleSetGoodsType = (val, item) => {
    confirm({
      title: '确认信息',
      icon: <ExclamationCircleOutlined />,
      content: `是否确认设为${goodsArr[val]}？`,
      cancelText: '取消',
      okText: '确定',
      onOk() {
        handleCheckGoods(val, item);
      },
    });
  };

  //检测是否有对应的匹配网店商品
  const handleCheckGoods = async (val, item) => {
    setLoading(true);
    const { success, data } = await affect({
      zjfGoodsMatchId: item.zjfGoodsMatchId ? item.zjfGoodsMatchId : 0,
    });
    setLoading(false);
    if (success) {
      if (data <= 1) {
        setGoodsType(val, item);
      } else {
        confirm({
          title: '确认信息',
          icon: <ExclamationCircleOutlined />,
          content: `检测到该网店商品匹配的供应商商品所对应的网店商品有${
            data - 1
          }个，它们的商品类型会同时修改，请确认是否设为${goodsArr[val]}？`,
          cancelText: '取消',
          okText: '确定',
          onOk() {
            setGoodsType(val, item);
          },
        });
      }
    }
  };

  //设置商品类型
  const setGoodsType = async (val, item) => {
    setLoading(true);
    const obj = {
      ids: item.id + '',
      zjfGoodsMatchIdS: item.zjfGoodsMatchId + '',
      type: val,
    };
    setLoading(false);
    const { success, data = {} } = await changeStatus(obj);
    if (success) {
      message.success('操作成功');
      handleData(1, item);
      const { composeIds = [], type, ecGoodsIds = [] } = data;
      getChannelStatistic(composeIds, type, ecGoodsIds, false);
    }
  };

  // 商品类型修改对订单的影响
  const getChannelStatistic = async (
    composeIds,
    type,
    ecGoodsIds,
    isAll,
    orderLength
  ) => {
    setLoading(true);
    const params = {
      composeIds: composeIds.toString(),
      type,
      ecGoodsIds: ecGoodsIds.toString(),
    };
    const { success, data = 0 } = await queryChannelStatistic(params);
    if (success && data > 0) {
      confirm({
        title: <p className={styles.orange}>确认信息</p>,
        icon: <ExclamationCircleOutlined />,
        content: (
          <div>
            <p className={styles.mb20}>
              原{isAll ? orderLength + '个' : ''}商品已匹配待审核{data}
              条订单，修改商品类型可能会影响这些订单，请确认是否需要影响？
            </p>
            <p className={styles.red}>注：</p>
            <p className={styles.red}>
              ①否：修改商品类型，将不影响订单页面的旧订单的商品类型
            </p>
            <p className={styles.red}>
              ②是：修改商品类型，将会使“待审核”的订单商品的商品类型修改为最新的商品类型，如果订单的发货渠道与商品渠道不一致，则会自动拆单
            </p>
          </div>
        ),
        cancelText: '否',
        okText: '是',
        onOk() {
          handleOrderUpdate(params);
        },
      });
    }
    setLoading(false);
  };

  // 修改商品类型的提交更新
  const handleOrderUpdate = async (params) => {
    setLoading(true);
    const { success } = await updateOrderGoods(params);
    if (success) {
      message.info('更新成功');
    }
    setLoading(false);
  };

  //点击批量设置
  const handleClick = (val) => {
    if (selectRowkeys.length > 0) {
      if (val == 3) {
        //批量设置发货渠道
        setVisible(val);
      } else if (val == 4) {
        //批量设为自发拿货
        confirm({
          title: '确认信息',
          icon: <ExclamationCircleOutlined />,
          content: '是否确认批量设为自发拿货？',
          cancelText: '取消',
          okText: '确定',
          onOk() {
            handleBatchGoodsType(1);
          },
        });
      } else if (val == 5) {
        //批量设为代发拿货
        confirm({
          title: '确认信息',
          icon: <ExclamationCircleOutlined />,
          content: '是否确认批量设为代发拿货？',
          cancelText: '取消',
          okText: '确定',
          onOk() {
            handleBatchGoodsType(2);
          },
        });
      } else if (val == 6) {
        confirm({
          title: '确认信息',
          icon: <ExclamationCircleOutlined />,
          content: '是否确认批量设为库存商品？',
          cancelText: '取消',
          okText: '确定',
          onOk() {
            handleBatchGoodsType(3);
          },
        });
      } else if (val == 7) {
        confirm({
          title: '确认信息',
          icon: <ExclamationCircleOutlined />,
          content: '是否确认批量设为供应商直发？',
          cancelText: '取消',
          okText: '确定',
          onOk() {
            handleBatchGoodsType(4);
          },
        });
      } else {
        return;
      }
    } else {
      message.info('请先选择需要批量操作的订单！');
    }
  };

  //批量设置自发（type=1）、代发(type=2)、库存商品(type =3)拿货、供应商直发(type =4)
  const handleBatchGoodsType = async (val) => {
    setLoading(true);
    const arr = [];
    for (let i in selectRowkeys) {
      const obj = find(data, ['id', selectRowkeys[i]]);
      arr.push(obj.zjfGoodsMatchId);
    }

    const obj = {
      ids: selectRowkeys.join(','),
      zjfGoodsMatchIdS: arr.join(','),
      type: val,
    };

    const { success, data: data1 = {} } = await changeStatus(obj);
    setLoading(false);
    if (success) {
      message.success('操作成功');
      //需要处理下数据
      handleData(2);
      const { composeIds = [], type, ecGoodsIds = [] } = data1;
      getChannelStatistic(
        composeIds,
        type,
        ecGoodsIds,
        true,
        selectRowkeys.length
      );
    }
  };

  //处理数据
  const handleData = (val, obj) => {
    if (val == 1) {
      //单个处理
      const arr = [...data];
      remove(arr, (v) => v.id == obj.id);
      handleUpdateData(arr);
      if (selectRowkeys.includes(obj.id)) {
        const arr = pull([...selectRowkeys], obj.id);
        setSelectRowkeys(arr);
      }
    } else {
      //批量处理
      const arr = [...data];
      for (let i in selectRowkeys) {
        const id = selectRowkeys[i];
        remove(arr, (v) => v.id == id);
      }
      handleUpdateData(arr);
      setSelectRowkeys([]);
    }
  };

  //表格数据
  const TableProps = {
    data,
    columns,
    size: 'small',
    rowKey: 'id',
    scroll: { x: 1040 },
    rowSelection: {
      type: 'checkbox',
      fixed: true,
      selectedRowKeys: selectRowkeys,
      onChange: (selectRowKeys) => {
        setSelectRowkeys(selectRowKeys);
      },
    },
  };

  // 顶部按钮
  const title = () => (
    <>
      {type == 3 ? (
        <Button style={{ marginRight: 10 }} onClick={setGoodsMind}>
          智能设置
        </Button>
      ) : null}
      {type == 3 ? (
        ''
      ) : (
        <Button style={{ marginRight: 10 }} onClick={() => handleClick(6)}>
          批量设为库存
        </Button>
      )}
      {type == 1 ? (
        ''
      ) : roleType == 'daifa' ? (
        ''
      ) : (
        <Button style={{ marginRight: 10 }} onClick={() => handleClick(4)}>
          批量设为自发拿货
        </Button>
      )}
      {type == 2 ? (
        ''
      ) : (
        <Button style={{ marginRight: 10 }} onClick={() => handleClick(5)}>
          批量设为代发拿货
        </Button>
      )}
      {type == 4 ? (
        ''
      ) : (
        <Button style={{ marginRight: 10 }} onClick={() => handleClick(7)}>
          批量设为供应商直发
        </Button>
      )}
      {type == 4 ? (
        ''
      ) : (
        <Button onClick={() => handleClick(3)}>批量修改发货渠道</Button>
      )}
    </>
  );

  //智能商品弹框设置
  const SetGoodsMindProps = {
    visible: visible == 2,
    roleType,
    handleOk() {
      setVisible(1);
    },
    handleCancel() {
      setVisible(1);
    },
  };

  //接口级别请求数据
  const getGoodsData = async (bool, obj = {}, arr) => {
    const { data, success } = await getGoodList({
      ids: bool ? obj.id : selectRowkeys.join(','),
      deliverType: type,
      page: 1,
      pageSize: 100,
    });
    if (success) {
      const { records = [] } = data;
      for (let i in records) {
        const index = findIndex(arr, ['id', records[i].id]);
        arr[index] = records[i];
      }
      handleUpdateData(arr);
    }
  };

  //设置发货渠道
  const EditChannelModalProps = {
    type,
    item,
    visible: visible == 3,
    ids: selectRowkeys.join(','),
    handleOk(bool, item) {
      const arr = [...data];
      getGoodsData(bool, item, arr);
      setItem({});
      setVisible(1);
    },
    handleCancel() {
      setItem({});
      setVisible(1);
    },
  };

  return (
    <>
      <div style={{ margin: '16px 0px' }}>{title()}</div>
      <CommonTable {...TableProps} />
      <SetGoodsMind {...SetGoodsMindProps} />
      <EditChannelModal {...EditChannelModalProps} />
      <CommonLoading loading={loading} />
    </>
  );
};
